package com.example.redisdemo01.controller;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/7/26 2:24
 * 基于注解方式操作 Redis
 */
@RestController
public class RedisAnnController {

    // 存和取缓存, 没有则存, 有则取缓存
    @RequestMapping("ann-get")
    @Cacheable(value = "spring.cache", key = "#name+'-'+#pnumber") // value 表示包
    public String get(String name, String pnumber) {
        if (!StringUtils.hasLength(name) || !StringUtils.hasLength(pnumber)) {
            return null;
        }
        System.out.println("执行了 get 方法");
        return "name=" + name + " | pnumber=" + pnumber;
    }

    // 更新缓存
    @RequestMapping("put")
    @CachePut(value = "spring.cache", key = "#name+'-'+#pnumber")
    public String put(String name, String pnumber) {
        if (!StringUtils.hasLength(name) || !StringUtils.hasLength(pnumber)) {
            return null;
        }
        System.out.println("执行了 put 方法");
        return "name=" + name + " <-> pnumber=" + pnumber;
    }

    // 缓存删除
    @RequestMapping("/del")
    @CacheEvict(value = "spring.cache", key = "#name+'-'+#pnumber")
    public void del(String name, String pnumber) {
        System.out.println("执行了缓存删除");
    }
}
